package com.pt.scraper;

import java.io.IOException;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.pt.site.page.IPage;
import com.pt.site.page.StandardPage;
import com.pt.site.resource.IResource;
import com.pt.site.resource.picture.StandardPicture;
import com.pt.site.resource.video.StandardVideo;

public class Main {
	
	private static Set<String> uniqueUrls;
	
	private static void resetUniqueUrls() {
		uniqueUrls = new HashSet<String>();
	}

	private static List<IPage> scrapeMainPage(String url, boolean recursive) throws IOException {
		if (uniqueUrls == null) {
			resetUniqueUrls();
		}
		Document doc = Jsoup.connect(url).get();
		Elements images = doc.getElementsByTag("img");
		List<IPage> galleries = new LinkedList<IPage>();
		for (Element img : images) {
			Element link = img.parent();
			String target = link.attr("target");
			String pageTitle = img.attr("title");
			if (!target.matches("_?blank") && !pageTitle.isEmpty()) {
				String cssClass = img.attr("class");
				String thumbnailUrl = img.attr("src");
				String pageUrl = link.attr("href");
				String description = img.attr("alt");
				IPage page = null;
				if (cssClass == null || cssClass.isEmpty() || cssClass.equals("thumb")) {
					// images
					page = new StandardPage(pageUrl, pageTitle, thumbnailUrl);
					scrapeImagePage(page);
				} else if (cssClass.equals("ThumbNail")) {
					// video
					page = new StandardPage(pageUrl, description, thumbnailUrl);
					page = scrapeVideoPage(page, description);
				}
				if (page != null) {
					galleries.add(page);
				}
			}
		}
		// TODO recursive
		return galleries;
	}
	
	private static IPage scrapeVideoPage(IPage page, String description) {
		String title = page.getTitle();
		IResource video = new StandardVideo(title, description);
		page.addResource(video);
		return page;
	}
	
	private static IPage scrapeImagePage(IPage page) throws IOException {
		Document doc = Jsoup.connect(page.getUrl()).get();
		Elements images = doc.getElementsByTag("img");
		String urlPrefix = page.getUrl() + "/";
		for (Element img : images) {
			String url = urlPrefix + img.parent().attr("href");
			String thumbnailUrl = urlPrefix + img.attr("src");
			IResource pic = new StandardPicture(url, thumbnailUrl);
			page.addResource(pic);
		}
		return page;
	}
	
	public static void main(String[] args) throws IOException {
		resetUniqueUrls();
		scrapeMainPage("http://www.petiteteenager.com", false);
	}
}
